package com.ok.activity.service.impl;

import com.ok.activity.domain.po.OkActivity;
import com.ok.activity.domain.po.OkUseractivity;
import com.ok.activity.mapper.OkUseractivityMapper;
import com.ok.activity.service.IOkActivityService;
import com.ok.activity.service.IOkUseractivityService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ok.api.client.IntegralClient;
import com.ok.api.domain.dto.OkIntegralDetailDTO;
import com.ok.common.config.IntegralNum;
import com.ok.common.exception.CustomException;
import com.ok.common.utils.UserContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户活动关系表 服务实现类
 * </p>
 *
 * @author lhw
 * @since 2024-04-29
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OkUseractivityServiceImpl extends ServiceImpl<OkUseractivityMapper, OkUseractivity> implements IOkUseractivityService {

    private final IOkActivityService okActivityService;
    private final IntegralClient integralClient;
    private final RabbitTemplate rabbitTemplate;

    @Override
    @GlobalTransactional
    public String join(Integer activityId) {
        OkUseractivity okUseractivity = new OkUseractivity();
        okUseractivity.setActivityId(activityId);
        okUseractivity.setUserId(UserContext.getUser());

        //向用户活动表中添加数据
        this.save(okUseractivity);

        //修改活动剩余数量
        OkActivity okActivity = okActivityService.getById(activityId);
        if (okActivity.getNum() == 0){
            throw new CustomException("活动已满");
        }
        okActivity.setNum(okActivity.getNum() - 1);
        okActivityService.updateById(okActivity);

        //增加用户积分
        integralClient.update(IntegralNum.INTEGRAL_ACTIVITY_JOIN);

        //构建积分详情信息
        OkIntegralDetailDTO detailDTO = new OkIntegralDetailDTO();
        detailDTO.setUserId(UserContext.getUser());
        detailDTO.setActivityId(activityId);
        detailDTO.setIntegral(IntegralNum.INTEGRAL_ACTIVITY_JOIN);
        try {
            rabbitTemplate.convertAndSend("integral_direct","",detailDTO);
        } catch (AmqpException e) {
            log.error("发送消息添加积分详细失败：{}",e.getMessage());
        }
        //返回活动凭证
        return okActivity.getVoucher();
    }
}
